<template>
  <van-popup
    round
    class="time-selector"
    v-model:show="visible"
    closeable
    position="bottom"
    :style="{ height: '80%' }"
  >
    <div class="head">
      选择配送时间
    </div>

    <div class="expect-time">
      预计送达时间：<span class="c-red">{{ getTimeText() }}</span>
    </div>

    <div class="time-box">
      <van-sidebar class="day-list" v-model="day" @change="onDayChange">
        <van-sidebar-item :title="getDayText(item)" v-for="(item, i) in dayList" :key="i" />
        <van-sidebar-item v-if="!isMoreDate" title="更多日期" @click="onMoreDate" />
      </van-sidebar>

      <div class="time-list">
        <div v-if="filterTimeList && filterTimeList.length">
          <div class="time-item" :class="{active: time === item.time}" v-for="item in filterTimeList" :key="item" @click="handleSelectTime(item)">{{ getSpliceTimeText(item.time) }}</div>
        </div>
        
        <van-empty v-else class="ta-c" description="暂无可配送时间，尝试更换日期，或联系客服" />
      </div>

    </div>

    <van-button class="confirm-btn" type="danger" block @click="handleConfirm">确定</van-button>
  </van-popup
  >
</template>

<script>
import {getCurrentDays} from '@/utils'
import {getSpliceTimeText} from '@/utils/time'
import {Toast} from 'vant'
import dayjs from 'dayjs'
import { getpreSubmitOrder } from "@/api/common";

const dayMap = {
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
  0: '周日',
}
export default {
  props: {
    orderData: {
      type: Object,
      default: () => {}
    },
    addressObj: {
      type: Object,
      default: () => {}
    },
    needBeforeThreeDay: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      isMoreDate: false,
      day: 0,
      time: '',
      dayList: [],
      timeList: []
    }
  },
  computed: {
    filterTimeList() {
      if (this.needBeforeThreeDay) {
        return this.timeList.filter(item => {
          const selectDate = dayjs(this.getSelectDate() + ' ' + item.time.slice(0, 8))
          const afterThreeDayDate = dayjs().add(3, 'day')
          return selectDate.unix() >= afterThreeDayDate.unix()
        })
      } else {
        return this.timeList
      }
    }
  },
  created() {
    this.getDayList(7)
  },
  methods: {
    getSpliceTimeText,
    show() {
      this.visible = true
      this.getDayList(this.isMoreDate ? 31 : 7)
      this.getTimeSlotList()
    },
    handleLocation() {
    },
    handleSelectType(index) {
      this.selectType = index
    },
    handleSelectTime(item) {
      this.time = item.time
    },
    handleConfirm() {
      if (!this.time) {
        Toast.fail('请选择配送时间段！')
        return
      }
      this.visible = false
      this.$emit('confirm', {
        timeText: this.getTimeText(),
        date: dayjs(this.dayList[this.day]).format('YYYY-MM-DD'),
        time: this.time
      })
    },
    getDayText(item) {
      const current = new Date()
      let text = ''
      if (current.getMonth() === item.getMonth()) {
        if (current.getDate() === item.getDate()) {
          text = '今天'
        } else if (current.getDate() + 1 === item.getDate()) {
          text = '明天'
        } else if (current.getDate() + 2 === item.getDate()) {
          text = '后天'
        }
      }
      return dayjs(item).format('MM-DD') + `(${text || dayMap[item.getDay()]})`
    },
    getTimeText () {
      const item = this.dayList[this.day]
      return `${this.getDayText(item)}  ${getSpliceTimeText(this.time)}`
    },
    getDayList(days) {
      let dayList = getCurrentDays(days)
      if (this.needBeforeThreeDay) {
        dayList = dayList.filter(item => {
          const nowDate = new Date()
          return item.getMonth() > nowDate.getMonth() ||
                (item.getMonth() == nowDate.getMonth() && item.getDate() >= nowDate.getDate() + 3)
        })
      }
      this.dayList = dayList
    },
    onMoreDate() {
      this.isMoreDate = true
      this.getDayList(31)
    },
    onDayChange() {
      this.time = ''
      this.getTimeSlotList()
    },
    getTimeSlotList() {
      if (!this.addressObj) {
        return
      }
      const selectDate = this.dayList[this.day]
      const params = {
        deliveryDate: dayjs(selectDate).format('YYYY-MM-DD'),
        cityName: this.addressObj.cityname || "",
        deptId: this.addressObj.id || "",
        latitude: this.orderData.latitude,
        longitude: this.orderData.longitude,
        selfDeliveryId: "",
      };
      getpreSubmitOrder(params).then((res) => {
        if (res.code == 200) {
          this.timeList = (res.data || []).filter(item => item.status);
        } else {
          this.timeList = []
        }
      })
    },
    getSelectDate() {
      const selectDate = this.dayList[this.day]
      return dayjs(selectDate).format('YYYY-MM-DD')
    }
  }
};
</script>

<style lang="less" scoped>
.time-selector {
  font-size: 12px;
  .head {
    line-height: 48px;
    text-align: center;
    font-weight: bold;
    border-bottom: 1px solid #f5f5f5;
    background: #fff;
  }
  .expect-time {
    line-height: 48px;
    font-weight: bold;
    padding-left: 18px;
    border-bottom: 1px solid #f5f5f5;
  }
  .time-box {
    height: calc(100% - 138px);
    .day-list {
      float: left;
      width: 120px;
      max-height: 100%;
    }
    .time-list {
      margin-left: 130px;
      max-height: 100%;
      overflow: auto;
      .time-item {
        line-height: 40px;
        font-weight: bold;
        &.active {
          color: #fc4f47;
        }
      }
    }
    .van-picker {
      margin-left: 160px;
    }
  }
  .confirm-btn {
    position: absolute;
    bottom: 0;
    width: 100%;
  }
}
</style>
